//
//  Datenbank.m
//  CoreDataCluster
//
//  Created by mm on 28.01.10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "Database.h"

@implementation Database

@synthesize modelFetchedResultsController;
@synthesize dataFetchedResultsController;
@synthesize voiceFetchedResultsController;

#pragma mark -
#pragma mark Core Data stack


Database *sharedDatabase;

+ (Database *)getDatabase {	
	
	@synchronized(self)
	{
		if (!sharedDatabase) {
			
			sharedDatabase = [[Database alloc] init];
			[sharedDatabase myInit];
		}		
	}	
	return sharedDatabase;
}


- (void)myInit {
	
	managedObjectContext = self.managedObjectContext;
	
	{
		NSError *error = nil;
		if (![[self modelFetchedResultsController] performFetch:&error]) {
			
			NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
			abort();
		}
	}
}

-(void) saveChanges {
	NSError *error;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
			NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
			abort();
        } 
    }
}

- (void)clearNews {
	
	NSArray *newsArray = [modelFetchedResultsController fetchedObjects];
	for (NSManagedObject *obj in newsArray) {
		[managedObjectContext deleteObject:obj];
	}
	NSError *error = nil;
	if (![modelFetchedResultsController performFetch:&error]) {		
		NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
		abort();
	}		
}

#pragma mark -
#pragma mark Database required methods

- (NSManagedObjectContext *) managedObjectContext {
	
    if (managedObjectContext != nil) {
        return managedObjectContext;
    }
	
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        managedObjectContext = [[NSManagedObjectContext alloc] init];
        [managedObjectContext setPersistentStoreCoordinator: coordinator];
    }
    return managedObjectContext;
}

- (NSManagedObjectModel *)managedObjectModel {
	
    if (managedObjectModel != nil) {
        return managedObjectModel;
    }
    managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];    
    return managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
	
    if (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
    }
	
	
	NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"iToli.sqlite"];
	/*
	 Set up the store.
	 For the sake of illustration, provide a pre-populated default store.
	 */
	NSFileManager *fileManager = [NSFileManager defaultManager];
	// If the expected store doesn't exist, copy the default store.
	if (![fileManager fileExistsAtPath:storePath]) {
		NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"iToli" ofType:@"sqlite"];
		if (defaultStorePath) {
			[fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
		}
	}
	
	NSURL *storeUrl = [NSURL fileURLWithPath:storePath];
	
	NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], 
							 NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];	
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
	
	NSError *error;
	if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) {
		NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
		abort();
    }    
	
    return persistentStoreCoordinator;
}

- (NSString *)applicationDocumentsDirectory {
	return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}

#pragma mark -
#pragma mark Fetched results controller

- (NSFetchedResultsController *)modelFetchedResultsController {
    
    if (modelFetchedResultsController != nil) {
        return modelFetchedResultsController;
    }
    
    /*
	 Set up the fetched results controller.
	 */
	// Create the fetch request for the entity.
	NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
	// Edit the entity name as appropriate.
	NSEntityDescription *entity = [NSEntityDescription entityForName:@"Model" inManagedObjectContext:managedObjectContext];
	
	[fetchRequest setEntity:entity];
	
	
	// Set the batch size to a suitable number.
	[fetchRequest setFetchBatchSize:200];
	
	NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"modelID" ascending:NO];
	NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:nameDescriptor, nil];
	
	[fetchRequest setSortDescriptors:sortDescriptors];
	
	// Edit the section name key path and cache name if appropriate.
    // nil for section name key path means "no sections".
	NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];
	//   aFetchedResultsController.delegate = self;
	self.modelFetchedResultsController = aFetchedResultsController;
	
	[aFetchedResultsController release];
	[fetchRequest release];
	[nameDescriptor release];
	[sortDescriptors release];
	
	return modelFetchedResultsController;
}
- (NSFetchedResultsController *)dataFetchedResultsController {
    
    if (dataFetchedResultsController != nil) {
        return dataFetchedResultsController;
    }
    
    /*
	 Set up the fetched results controller.
	 */
	// Create the fetch request for the entity.
	NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
	// Edit the entity name as appropriate.
	NSEntityDescription *entity = [NSEntityDescription entityForName:@"Data" inManagedObjectContext:managedObjectContext];
	
	[fetchRequest setEntity:entity];
	
	
	// Set the batch size to a suitable number.
	[fetchRequest setFetchBatchSize:200];
	
	NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"data" ascending:NO];
	NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:nameDescriptor, nil];
	
	[fetchRequest setSortDescriptors:sortDescriptors];
	
	NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];
	//   aFetchedResultsController.delegate = self;
	self.dataFetchedResultsController = aFetchedResultsController;
	
	[aFetchedResultsController release];
	[fetchRequest release];
	//[nameDescriptor release];
	//[sortDescriptors release];
	
	return dataFetchedResultsController;
}
- (NSFetchedResultsController *)voiceFetchedResultsController {
    
    if (dataFetchedResultsController != nil) {
        return dataFetchedResultsController;
    }
    
    /*
	 Set up the fetched results controller.
	 */
	// Create the fetch request for the entity.
	NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
	// Edit the entity name as appropriate.
	NSEntityDescription *entity = [NSEntityDescription entityForName:@"Voice" inManagedObjectContext:managedObjectContext];
	
	[fetchRequest setEntity:entity];
	
	
	// Set the batch size to a suitable number.
	[fetchRequest setFetchBatchSize:200];
	
	NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"voice" ascending:NO];
	NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:nameDescriptor, nil];
	
	[fetchRequest setSortDescriptors:sortDescriptors];
	
	NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];
	//   aFetchedResultsController.delegate = self;
	self.dataFetchedResultsController = aFetchedResultsController;
	
	[aFetchedResultsController release];
	[fetchRequest release];
	//[nameDescriptor release];
	//[sortDescriptors release];
	
	return dataFetchedResultsController;
}
-(NSData *)findLastImage{
	NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
	NSEntityDescription *entity = [NSEntityDescription entityForName:@"Data" inManagedObjectContext:managedObjectContext];
	[fetchRequest setEntity:entity];
	NSManagedObject *image = nil;
	NSError *error;
	
	NSArray *objects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
	
	if ([objects count] != 0) {
		image = [objects objectAtIndex:[objects count]-1];
		NSData *data = [image valueForKey:@"data"];
		return data;
	}
	[fetchRequest release];
	[entity release];
	[objects release];
	return nil;
}

-(NSData *)findLastVoice{
	NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
	NSEntityDescription *entity = [NSEntityDescription entityForName:@"Voice" inManagedObjectContext:managedObjectContext];
	[fetchRequest setEntity:entity];
	NSManagedObject *image = nil;
	NSError *error;
	
	NSArray *objects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
	
	if ([objects count] != 0) {
		image = [objects objectAtIndex:[objects count]-1];
		NSData *data = [image valueForKey:@"voice"];
		return data;
	}
	[fetchRequest release];
	[entity release];
	[objects release];
	return nil;
}


#pragma mark -
#pragma mark Memory management

- (void)dealloc {
	
	[modelFetchedResultsController release];
	[managedObjectContext release];
    [managedObjectModel release];
    [persistentStoreCoordinator release];
    [super dealloc];
}


@end
